package cn.darven.ui;

import javax.swing.*;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author darven
 * @date 2025/11/3
 * @description TODO
 */
public class DownloadManager {
    private MainFrame mainFrame;

    public DownloadManager(MainFrame mainFrame) {
        this.mainFrame = mainFrame;
    }

    public void downloadXML() {
        DatabaseManager databaseManager = mainFrame.getDatabaseManager();
        if (databaseManager.getSqlServerDB() == null) {
            JOptionPane.showMessageDialog(mainFrame, "请先连接数据库");
            return;
        }
        mainFrame.updateStatus("正在执行查询");
        String s = databaseManager.getSqlServerDB().fetchXmlData();
        mainFrame.updateStatus("查询完成");

        mainFrame.updateStatus("开始下载");
        String formatXml = databaseManager.getXsltTransformer().formatXml(s);
        mainFrame.updateStatus("XML格式化完成");

        JFileChooser folderChooser = new JFileChooser();
        folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        folderChooser.setAcceptAllFileFilterUsed(false);
        int i = folderChooser.showOpenDialog(mainFrame);
        if (i != JFileChooser.APPROVE_OPTION) {
            JOptionPane.showMessageDialog(mainFrame, "请选择文件夹");
            return;
        }
        File selectedFolder = folderChooser.getSelectedFile();
        String outputPath = selectedFolder.getAbsolutePath() + "/contact.xml";
        File outputFile = new File(outputPath);
        // 检查文件是否存在
        if (outputFile.exists()) {
            int choice = JOptionPane.showConfirmDialog(
                    mainFrame,
                    "文件 output.html 已存在，是否覆盖？",
                    "文件已存在",
                    JOptionPane.YES_NO_CANCEL_OPTION
            );

            if (choice == JOptionPane.CANCEL_OPTION || choice == JOptionPane.NO_OPTION) {
                // 如果用户选择不覆盖，创建带时间戳的新文件
                String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                outputPath = selectedFolder.getAbsolutePath() + "/contact" + timestamp + ".xml";
            }
        }


        try {
            mainFrame.updateStatus("正在生成XML文件...");
            try (FileWriter fileWriter = new FileWriter(outputPath)) {
                fileWriter.write(formatXml);
            }
            mainFrame.updateStatus("HTML文件生成完成");
            JOptionPane.showMessageDialog(mainFrame, "文件已保存到: " + outputPath);
        } catch (Exception ex) {
            mainFrame.updateStatus("XML文件生成失败: " + ex.getMessage());
            JOptionPane.showMessageDialog(mainFrame, "生成失败: " + ex.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void downloadHtml() {
        DatabaseManager databaseManager = mainFrame.getDatabaseManager();
        if (databaseManager.getSqlServerDB() == null) {
            JOptionPane.showMessageDialog(mainFrame, "请先连接数据库");
            return;
        }

        JFileChooser folderChooser = new JFileChooser();
        folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        folderChooser.setAcceptAllFileFilterUsed(false);
        int i = folderChooser.showOpenDialog(mainFrame);
        if (i != JFileChooser.APPROVE_OPTION) {
            JOptionPane.showMessageDialog(mainFrame, "请选择文件夹");
            return;
        }

        File selectedFolder = folderChooser.getSelectedFile();
        String outputPath = selectedFolder.getAbsolutePath() + "/output.html";
        File outputFile = new File(outputPath);

        // 检查文件是否存在
        if (outputFile.exists()) {
            int choice = JOptionPane.showConfirmDialog(
                    mainFrame,
                    "文件 output.html 已存在，是否覆盖？",
                    "文件已存在",
                    JOptionPane.YES_NO_CANCEL_OPTION
            );

            if (choice == JOptionPane.CANCEL_OPTION || choice == JOptionPane.NO_OPTION) {
                // 如果用户选择不覆盖，创建带时间戳的新文件
                String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                outputPath = selectedFolder.getAbsolutePath() + "/output_" + timestamp + ".html";
            }
        }

        try {
            mainFrame.updateStatus("正在生成HTML文件...");
            databaseManager.getXsltTransformer().transformToHtmlFile(
                    databaseManager.getSqlServerDB().fetchXmlData(),
                    "src/main/resources/xslt/contact.xsl",
                    outputPath
            );
            mainFrame.updateStatus("HTML文件生成完成");
            JOptionPane.showMessageDialog(mainFrame, "文件已保存到: " + outputPath);
        } catch (Exception ex) {
            mainFrame.updateStatus("HTML文件生成失败: " + ex.getMessage());
            JOptionPane.showMessageDialog(mainFrame, "生成失败: " + ex.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
